import { Injectable, OnInit } from "@angular/core";
import { HttpClient } from '@angular/common/http';

import { ProductConstants } from "src/app/utils/Constants";

import { Product } from "./Product";

// 购物车
@Injectable({
  providedIn: 'root'
})
export class CartService {
  http: HttpClient
  items: Product[] = [];

  constructor(
    http: HttpClient
  ) {
    this.http = http

    console.error("CartService.ts ==> ngOnInit()");
    let data = localStorage.getItem(ProductConstants.LOCAL_STORAGE_KEY);
    console.error('data', data);

    if (data) {
      this.items = JSON.parse(data);
    }
  }

  ngOnInit() {
    
  }

  addToCart(product: Product) {
    this.items.push(product);
    localStorage.setItem(ProductConstants.LOCAL_STORAGE_KEY, JSON.stringify(this.items))
  }

  getItems() {
    return this.items;
  }

  clearCart() {
    this.items = [];
    localStorage.removeItem(ProductConstants.LOCAL_STORAGE_KEY);
    return this.items;
  }

  // 配送方案及其价格
  getShippingPrices() {
    return this.http.get<{type: string, price: number}[]>('/assets/shipping.json');
  }
}